<template>
  <div class="app-container">
    <!--搜索区域-->
    <el-form size="mini" :inline="true" :model="searchForm">
      <el-form-item>
        <el-input v-model="searchForm.username" placeholder="账号" @keyup.enter.native="handleSearch"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="searchForm.email" placeholder="邮箱" @keyup.enter.native="handleSearch"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch" :loading="searchButtonLoading">查询
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" icon="el-icon-plus" @click="showDialogForm()">添加</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" icon="el-icon-delete" @click="handleDelete()">删除</el-button>
      </el-form-item>
    </el-form>
    <!--数据表格-->
    <el-table size="mini" border v-loading="tableLoading" element-loading-text="加载中，请稍后..."
              :data="tableData">
      <el-table-column prop="id" type="selection" fixed/>
      <el-table-column label="ID" prop="id"/>
      <el-table-column label="账号" prop="username"/>
      <el-table-column label="昵称" prop="nickname"/>
      <el-table-column label="姓名" prop="reallyName"/>
      <el-table-column label="电话" width="100" prop="phone"/>
      <el-table-column label="头像" align="center">
        <template slot-scope="scope">
          <el-avatar :size="25" :src="scope.row.avatar"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="昵称">
        <template slot-scope="scope">
          <span>{{ scope.row.nickname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" width="150">
        <template slot-scope="scope">
          {{ scope.row.email }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="60" align="center" class-name="status-col">
        <template slot-scope="scope">
          <el-tag size="mini" :type="scope.row.status | statusTypeFilter">{{ scope.row.status | statusTextFilter}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="角色" width="230">
        <template slot-scope="scope">
          <el-tag type="info" size="mini" effect="dark" style="margin-right: 2px"
                  :type="role | roleTypeFilter" v-for="role in scope.row.roles">
            {{role}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="created_at" width="150">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ createTimeFormatter(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="created_at" width="150">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ updateTimeFormatter(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="50" fixed="right" align="center">
        <template slot-scope="scope">
          <el-tooltip content="编辑" placement="top">
            <i class="el-icon-edit" @click="showDialogForm(scope.row)" style="cursor: pointer"></i>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <i class="el-icon-delete" @click="handleDelete(scope.row.id)" style="cursor: pointer"></i>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination background
                   layout="prev, pager, next, sizes, total"
                   :page-sizes="[10, 20, 50, 100]"
                   :current-page="currentPage"
                   :page-size="pageSize"
                   :total="total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"/>
    <!--编辑模态框-->
    <el-dialog :title="editDialogTitle" center width="550px"
               :visible.sync="editDialogVisible" :close-on-press-escape="false" :close-on-click-modal="false">
      <el-form size="mini" :inline="true" status-icon
               :model="editDialogForm" :rules="editDialogRules" ref="editDialogForm">
        <el-form-item label="账号" :label-width="editDialogFormLabelWidth" prop="username">
          <el-input v-model="editDialogForm.username" autocomplete="off" placeholder="账号"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="editDialogFormLabelWidth" prop="password">
          <el-input v-model="editDialogForm.password" autocomplete="off" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item label="昵称" :label-width="editDialogFormLabelWidth" prop="nickname">
          <el-input v-model="editDialogForm.nickname" autocomplete="off" placeholder="昵称"></el-input>
        </el-form-item>
        <el-form-item label="姓名" :label-width="editDialogFormLabelWidth" prop="reallyName">
          <el-input v-model="editDialogForm.reallyName" autocomplete="off" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="头像" :label-width="editDialogFormLabelWidth" prop="avatar">
          <el-input v-model="editDialogForm.avatar" autocomplete="off" placeholder="头像"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="editDialogFormLabelWidth" prop="phone">
          <el-input v-model="editDialogForm.phone" autocomplete="off" placeholder="电话"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="editDialogFormLabelWidth" prop="email">
          <el-input v-model="editDialogForm.email" autocomplete="off" placeholder="邮箱"></el-input>
        </el-form-item>
        <el-form-item label="性别" :label-width="editDialogFormLabelWidth" prop="sex">
          <el-select v-model="editDialogForm.sex" placeholder="请选择性别">
            <el-option label="男" :value="0"></el-option>
            <el-option label="女" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" :label-width="editDialogFormLabelWidth" prop="age">
          <el-input v-model="editDialogForm.age" autocomplete="off" placeholder="年龄"></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-width="editDialogFormLabelWidth" prop="status">
          <el-select v-model="editDialogForm.status" placeholder="请选择状态">
            <el-option label="正常" :value="0"></el-option>
            <el-option label="冻结" :value="1"></el-option>
            <el-option label="删除" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" :label-width="editDialogFormLabelWidth" prop="roleIds">
          <el-select v-model="editDialogForm.roleIds" multiple placeholder="请选择角色" value-key="id">
            <el-option v-for="item in roles" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" size="mini" @click="handleEdit('editDialogForm')" :loading="editDialogButtonLoading">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listUser, editUser } from '@/api/user'
  import { formatDate } from '@/utils/cliUtils'

  export default {
    filters: {
      statusTypeFilter(status) {
        const statusMap = {
          0: 'success',
          1: 'gray',
          2: 'danger'
        }
        return statusMap[status]
      },
      statusTextFilter(status) {
        const statusTextMap = {
          0: '正常',
          1: '冻结',
          2: '删除'
        }
        return statusTextMap[status]
      },
      roleTypeFilter(role) {
        const roleTypeMap = {
          'ADMIN': '',
          'TEACHER': 'success',
          'STUDENT': 'warning'
        }
        return roleTypeMap[role]
      }
    },
    data() {
      return {
        tableLoading: true,
        tableData: null,
        currentPage: 1,
        pageSize: 10,
        total: 0,
        searchForm: {
          username: '',
          email: ''
        },
        searchButtonLoading: false,
        editDialogVisible: false,
        editDialogTitle: '',
        editDialogFormLabelWidth: '60px',
        editDialogForm: {
          id: '',
          username: '',
          password: '',
          nickname: '',
          reallyName: '',
          avatar: '',
          phone: '',
          email: '',
          sex: '',
          age: '',
          status: '',
          roleIds: []
        },
        editDialogRules: {
          username: [
            { required: true, message: '请输入账号', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ],
          nickname: [
            { required: true, message: '请输入昵称', trigger: 'blur' }
          ],
          reallyName: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          avatar: [
            { required: true, message: '请输入头像', trigger: 'blur' }
          ],
          phone: [
            { required: true, message: '请输入电话', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' }
          ],
          sex: [
            { required: true, message: '请选择性别', trigger: 'blur' }
          ],
          age: [
            { required: true, message: '请输入年龄', trigger: 'blur' }
          ],
          status: [
            { required: true, message: '请选择状态', trigger: 'blur' }
          ],
          roleIds: [
            { required: true, message: '请选择角色', trigger: 'blur' }
          ]
        },
        editDialogButtonLoading: false,
        roleIds: '',
        roles: [{
          value: '0',
          label: 'ADMIN'
        }, {
          value: '1',
          label: 'TEACHER'
        }, {
          value: '2',
          label: 'STUDENT'
        }]
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      fetchData() {
        this.tableLoading = true
        listUser({ username: this.searchForm.username, email: this.searchForm.email }).then(response => {
          this.tableData = response.data
          this.total = response.total
          this.tableLoading = false
          this.searchButtonLoading = false
        }).catch(() => {
          this.tableLoading = false
          this.searchButtonLoading = false
        })
      },
      createTimeFormatter(row) {
        let date = new Date(row.createTime)
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      },
      updateTimeFormatter(row) {
        let date = new Date(row.updateTime)
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.fetchData()
      },
      handleSearch() {
        this.searchButtonLoading = true
        this.fetchData()
      },
      showDialogForm(row) {
        this.editDialogVisible = true
        if (row == undefined) {
          this.editDialogTitle = '添加用户'
          this.editDialogForm.id = ''
          this.editDialogForm.username = ''
          this.editDialogForm.password = ''
          this.editDialogForm.nickname = ''
          this.editDialogForm.reallyName = ''
          this.editDialogForm.avatar = ''
          this.editDialogForm.phone = ''
          this.editDialogForm.email = ''
          this.editDialogForm.sex = ''
          this.editDialogForm.age = ''
          this.editDialogForm.status = ''
          this.editDialogForm.roleIds = []
          this.roleIds = ''
        } else {
          this.editDialogTitle = '更新用户'
          this.editDialogForm.id = row.id
          this.editDialogForm.username = row.username
          this.editDialogForm.password = row.password
          this.editDialogForm.nickname = row.nickname
          this.editDialogForm.reallyName = row.reallyName
          this.editDialogForm.avatar = row.avatar
          this.editDialogForm.phone = row.phone
          this.editDialogForm.email = row.email
          this.editDialogForm.sex = row.sex
          this.editDialogForm.age = row.age
          this.editDialogForm.status = row.status
          this.editDialogForm.roleIds = row.roles
          console.log(row.roles)
          this.roleIds = ''
        }
      },
      handleEdit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.editDialogButtonLoading = true
            for (let i = 0; i < this.editDialogForm.roleIds.length; i++) {
              this.roleIds += this.editDialogForm.roleIds[i] + ','
            }
            console.log(this.roleIds)
            let params = {
              username: this.editDialogForm.username,
              password: this.editDialogForm.password,
              nickname: this.editDialogForm.nickname,
              reallyName: this.editDialogForm.reallyName,
              avatar: this.editDialogForm.avatar,
              phone: this.editDialogForm.phone,
              email: this.editDialogForm.email,
              sex: this.editDialogForm.sex,
              age: this.editDialogForm.age,
              status: this.editDialogForm.status,
              roleIds: this.roleIds
            }
            editUser(params).then(response => {
              this.$message({ type: 'success', message: response.msg })
              this.editDialogVisible = false
              this.editDialogButtonLoading = false
              this.fetchData()
            }).catch(() => {
              this.editDialogButtonLoading = false
            })
          } else {
            return false
          }
        })
      }
    }
  }
</script>

<style scoped lang="scss">
  .el-pagination {
    margin-left: -10px;
    margin-top: 5px;
  }

  .el-select {
    width: 159px;
  }
</style>
